package com.thank.concurrency.samples.atomic;

import com.thank.concurrency.annoations.NotThreadSafe;
import com.thank.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author thank
 * 用普通Boolean标志
 * 演示多个线程下，这个业务只有一个线程进行处理的[非线程安全]情况
 */
@Slf4j
@NotThreadSafe
public class AtomicExample7 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;


    private static Boolean isHappened = false;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    doSomething();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception: ", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("isHappened: {}", isHappened);
    }


    /**
     * 这段方法只会执行一次
     */
    public static void doSomething() {
        if (!isHappened) {
            log.info("---doSomething()---");
        }
        isHappened = true;
    }
}
